package com.situ.feemanagement.interceptor;

import com.situ.feemanagement.pojo.Auth;
import com.situ.feemanagement.pojo.User;
import com.situ.feemanagement.service.IAuthService;
import com.situ.feemanagement.service.IUserService;
import com.situ.feemanagement.util.CookieUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {

    private IUserService userService;
    private IAuthService authService;

    public LoginInterceptor(IUserService userService, IAuthService authService) {
        this.userService = userService;
        this.authService = authService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user == null) {
            Cookie cookie = CookieUtils.getCookie(request,"autoLogin");
            if (cookie != null) {
                String[] values = cookie.getValue().split("&");
                String name = values[0];
                String password = values[1];
                //IUserService userService = new UserServiceImpl();
                user = userService.login(name, password);
                if (user != null) {
                    session.setAttribute("user",user);
                    //IAuthService authService = new AuthServiceImpl();
                    List<Auth> authList = authService.selectByRole(user.getRole());
                    session.setAttribute("authList",authList);
                    return true;
                }
            }
            response.sendRedirect("/page/login");
            return false;
        }
        return true;
    }
}
